﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AlbumArtOrganizer.Plugins.WindowsMediaPlayer.AlbumScanner
{
    public class AlbumScanner : AlbumArtOrganizer.AlbumScanner.AlbumScanner, AlbumArtOrganizer.AlbumScanner.IAlbumScanner
    {
        public override IEnumerable<AlbumArtOrganizer.Model.IAlbum> GetAlbums()
        {
            var windowsMediaPlayer = new WMPLib.WindowsMediaPlayer();
            var mediaCollection = windowsMediaPlayer.mediaCollection;
            var playlistAll = mediaCollection.getAll();
            var dictionaryArtists = new Dictionary<string, Model.Artist>();
            var dictionaryAlbums = new Dictionary<string, Model.Album>();
            for (int i = 0; i < playlistAll.count; i++)
            {
                var reportProgressEventArgs = new AlbumArtOrganizer.AlbumScanner.AlbumScannerReportProgressEventArgs()
                {
                    PercentageComplete = (double)i / (double)playlistAll.count
                };
                var mediaItem = playlistAll.Item[i];
                var albumName = mediaItem.getItemInfo("WM/AlbumTitle");
                if (String.IsNullOrEmpty(albumName))
                {
                    OnReportProgress(reportProgressEventArgs);
                    continue;
                }
                var artistName = mediaItem.getItemInfo("WM/AlbumArtist");
                if (String.IsNullOrEmpty(artistName))
                {
                    OnReportProgress(reportProgressEventArgs);
                    continue;
                }
                var fullAlbumString = String.Format("{0} - {1}", artistName, albumName);
                Model.Album album;
                Model.Artist artist;
                if (dictionaryAlbums.ContainsKey(fullAlbumString))
                {
                    OnReportProgress(reportProgressEventArgs);
                    continue;
                }
                if (!dictionaryArtists.ContainsKey(artistName))
                {
                    artist = new Model.Artist()
                    {
                        Name = artistName
                    };
                    dictionaryArtists.Add(artistName, artist);
                }
                else
                {
                    artist = dictionaryArtists[artistName];
                }
                DateTime? releaseDate = null;
                DateTime releaseDateResult;
                if (DateTime.TryParse(mediaItem.getItemInfo("ReleaseDate"), out releaseDateResult))
                {
                    releaseDate = releaseDateResult;
                }
                var localAppDataPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
                var trackingID = mediaItem.getItemInfo("TrackingID");
                var coverPath = String.Format(@"{0}\Microsoft\Media Player\Art Cache\LocalMLS\{1}.jpg", localAppDataPath, trackingID);
                album = new Model.Album()
                {
                    Title = albumName,
                    Artist = artist,
                    ReleaseDate = releaseDate,
                    CoverImage = new Model.CoverImage()
                    {
                        Path = coverPath
                    }
                };
                dictionaryAlbums.Add(fullAlbumString, album);
                reportProgressEventArgs.Album = album;
                reportProgressEventArgs.FoundCount = dictionaryAlbums.Count;
                OnReportProgress(reportProgressEventArgs);
            }
            var completedEventArgs = new AlbumArtOrganizer.AlbumScanner.AlbumScannerCompletedEventArgs()
            {
                Albums = dictionaryAlbums.Values.Cast<AlbumArtOrganizer.Model.IAlbum>()
            };
            OnCompleted(completedEventArgs);
            return dictionaryAlbums.Values.Cast<Model.Album>();
        }

        public override void ReplaceCoverImage(AlbumArtOrganizer.Model.IAlbum album, AlbumArtOrganizer.Model.IImage image)
        {
            if (album is Model.Album)
            {
                var coverImage = album.CoverImage as Model.CoverImage;
                var webClient = new System.Net.WebClient();
                webClient.DownloadFile(image.FullSizeLocation, coverImage.Path);
                coverImage.PublishPathChangedNotfication();
            }
            else
            {
                throw new InvalidOperationException("Cannot call ReplaceCoverImage for FileSystem plug-in with an IAlbum implementation from another plug-in.");
            }
        }
    }
}
